package yc.gg.service.impl;

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import yc.gg.domain.DTO.UserDTO;
import yc.gg.domain.DTO.UserFansDTO;
import yc.gg.domain.po.UserFollow;
import yc.gg.mapper.UserFollowMapper;
import yc.gg.service.FollowService;
import yc.gg.utils.Result;
import yc.gg.utils.UserHolder;

import java.util.*;

//TODO:控制层、sql表

/**
 * @author Lee
 */
@Service("followService")
@RequiredArgsConstructor
public class FollowServiceImpl implements FollowService {

    private final UserFollowMapper userFollowMapper;
    private final StringRedisTemplate stringRedisTemplate;


    @Override
    public Result followUser(String followUserId, Boolean isFollow) {
        String userId = UserHolder.getUser().getOpenid();
        String key = "follows:user:" + userId;
        String key1 = "fans:user:" + followUserId;

        if (Objects.equals(userId, followUserId)) {
            return Result.error("自己不能关注自己");
        }

        // 没关注
        if (isFollow) {
            UserFollow userFollow = new UserFollow();
            userFollow.setFollowUserId(followUserId);
            userFollow.setUserId(userId);

            boolean isSuccess = userFollowMapper.insert(userFollow);
            if (isSuccess) {
                // 关注用户id放入set
                stringRedisTemplate.opsForSet().add(key, followUserId);
                stringRedisTemplate.opsForSet().add(key1, userId);
                followFeed(followUserId);
            }
        } else {
            // 取关
            boolean isOk = userFollowMapper.noFollow(userId, followUserId);
            if (isOk) {
                // 关注用户id移除set
                stringRedisTemplate.opsForSet().remove(key, followUserId);
                stringRedisTemplate.opsForSet().remove(key1, userId);
            }
        }
        return Result.success(isFollow ? "关注成功" : "取消关注");
    }

    @Override
    public Result isFollowUser(String followUserId) {
        String userId = UserHolder.getUser().getOpenid();
        Integer count = userFollowMapper.isFollow(userId, followUserId);
        return Result.success(count > 0);
    }

    @Override
    public Boolean isMutualFollow(String curUserId, String followUserId) {
        return userFollowMapper.isMutualFollow(curUserId, followUserId) > 0;
    }

    @Override
    public Boolean isFollowUser(String curUserId, String followUserId) {
        return userFollowMapper.isFollow(curUserId, followUserId) > 0;
    }

    @Override
    public Result myFans() {
        String userId = UserHolder.getUser().getOpenid();
        String key = "fans:user:" + userId;

        Set<String> fansSet = stringRedisTemplate.opsForSet().members(key);
        List<Long> fansList = new ArrayList<>();
        if (fansSet != null) {
            for (String fan : fansSet) {
                fansList.add(Long.parseLong(fan));
            }
        }

        return Result.success(fansList);
    }

    /**
     * 获取用户关注的用户ID
     */
    @Override
    public Set<String> selectUserAttention(String userId) {
        return userFollowMapper.selectUserAttention(userId);
    }

    @Override
    public Result followCommonUser(String id) {
        String userId = UserHolder.getUser().getOpenid();
        String key = "follows:user:" + userId;
        String key1 = "follows:user:" + id;

        // key和key1的交集
        Set<String> intersection = stringRedisTemplate.opsForSet().intersect(key, key1);

        // 无共同关注
        if (intersection == null || intersection.isEmpty()) {
            return Result.success(Collections.emptyList());
        }

        // 有共同关注
        List<Long> ids = intersection.stream().map(Long::valueOf).toList();
        // 查询共同关注的用户信息
        List<UserDTO> users = userFollowMapper.selectByIds(ids);
        return Result.success(users);
    }


    @Override
    public Result isOtherFollow(String id) {
        String userId = UserHolder.getUser().getOpenid();

        String key = "follows:user:" + userId;
        String key1 = "fans:user:" + id;

        boolean currentUserFollowsTarget = Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(key, id));
        boolean targetUserFollowsCurrentUser = Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(key1, userId));

        // 判断是否互相关注
        boolean isMutualFollow = currentUserFollowsTarget && targetUserFollowsCurrentUser;

        return Result.success(isMutualFollow);
    }

    @Override
    public Result other() {
        String userId = UserHolder.getUser().getOpenid();

        String followsKey = "follows:user:" + userId;
        Set<String> followsSet = stringRedisTemplate.opsForSet().members(followsKey);

        List<Long> mutualFollowersList = new ArrayList<>();

        if (followsSet != null) {
            for (String followerIdStr : followsSet) {
                Long followerId = Long.parseLong(followerIdStr);
                if (followerId.equals(userId)) {
                    continue; // 忽略自己
                }

                String fansKey = "fans:user:" + followerId;
                boolean isMutualFollow = Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(fansKey, userId));

                if (isMutualFollow) {
                    mutualFollowersList.add(followerId);
                }
            }
        }
        return Result.success(mutualFollowersList);
    }

    @Override
    public Result myfansMsg() {
        String userId = UserHolder.getUser().getOpenid();
        String key = "fans:user:" + userId;
        String key1 = "follows:user:" + userId;

        Set<String> fansSet = stringRedisTemplate.opsForSet().members(key);
        Set<String> followSet = stringRedisTemplate.opsForSet().members(key1);

        List<UserFansDTO> other = new ArrayList<>();
        List<UserFansDTO> followList = new ArrayList<>();
        List<UserFansDTO> fansList = new ArrayList<>();

        if (fansSet != null) {
            for (String fan : fansSet) {
                if (!CollUtil.isEmpty(followSet)) {
                    for (String follow : followSet) {
                        // 互相关注
                        if (Objects.equals(fan, follow)) {
                            UserFansDTO user = userFollowMapper.getUserMessage(fan);
                            user.setId(follow);
                            other.add(user);
                        }
                    }
                }

                // 粉丝
                UserFansDTO user = userFollowMapper.getUserMessage(fan);
                user.setId(fan);
                fansList.add(user);

            }

            // 关注
            if (!CollUtil.isEmpty(followSet)) {
                for (String follow : followSet) {
                    UserFansDTO user1 = userFollowMapper.getUserMessage(follow);
                    user1.setId(follow);
                    followList.add(user1);
                }
            }

        }
        fansList.removeAll(other);
        followList.removeAll(other);
        HashMap<String, List<UserFansDTO>> hm = new HashMap<>();
        hm.put("1", followList);
        hm.put("2", fansList);
        hm.put("3", other);

        return Result.success(hm);
    }

    //推送到消息页
    private void followFeed(String userId){
        //当前用户
        String id = UserHolder.getUser().getOpenid();
        //推送关注信息
        String key = "Feed:follow:"+userId;
        HashMap<String,String> hm =new HashMap<>();
        hm.put("userId", id);
        //是否已读 1未读 2已读
        hm.put("isRead","1");
        stringRedisTemplate.opsForZSet().add(key,hm.toString(),System.currentTimeMillis());
    }
}


